package com.home.fansea.controller;


import cn.hutool.json.JSONUtil;
import com.home.fansea.entity.DeviceInfo;
import com.home.fansea.utils.MyMQTTClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.LinkedList;
import java.util.Queue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author WXY
 * @date 2022/6/29 20:44
 */
@RestController
@RequestMapping("/mqtt")
public class MqttController {

    private static final ExecutorService threadPoolExecutor = Executors.newFixedThreadPool(5);


    @Autowired
    private MyMQTTClient myMQTTClient;

/*    @Value("${mqtt.topic1}")
    String topic1;
    @Value("${mqtt.topic2}")
    String topic2;
    @Value("${mqtt.topic3}")
    String topic3;*/
    @Value("${mqtt.topic4}")
    String topic4;


    Queue<String> msgQueue = new LinkedList<>();
    int count = 1;

    @PostMapping("/pubMsg")
    @ResponseBody
    public synchronized void mqttMsg(@RequestBody DeviceInfo mqttMsg) {
        System.out.println("队列元素数量：" + msgQueue.size());
//        System.out.println("***************" + mqttMsg.getName() + ":" + mqttMsg.getContent() + "****************");
        mqttMsg.setTime(new Date());
        String sendMsg = JSONUtil.toJsonStr(mqttMsg);
        System.out.println(sendMsg);
        //队列添加元素
        boolean flag = msgQueue.offer(sendMsg);
        if (flag) {
            //发布消息  topic2 是你要发送到那个通道里面的主题 比如我要发送到topic2主题消息
            myMQTTClient.publish(msgQueue.poll(), "mqtt/device");
            System.out.println("时间戳" + System.currentTimeMillis());
        }
        System.out.println("队列元素数量：" + msgQueue.size());
    }
}
